import it.polito.appeal.traci.SumoTraciConnection;
import it.polito.appeal.traci.VehicleLifecycleObserver;
import it.polito.appeal.traci.connectedcar.sumo.SUMOVehicle;
import it.polito.appeal.traci.connectedcar.vehicle.ConnectedVehicle;

import java.net.Inet4Address;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


public class SimulationManager implements VehicleLifecycleObserver {

	private SumoTraciConnection conn;
	private static SimulationManager simulationManager;
	private Map<String,ConnectedVehicle>connectedCars;
	public static void main(String[] args) {
		
		simulationManager = new SimulationManager();
		
	}
	public SimulationManager() {
		
		//conn = new SumoTraciConnection("simulation-files/quickstart.sumo.cfg.xml", 12345, false);
		//conn.addVehicleLifecycleObserver(this);
		//conn.runServer();
		try {
			conn = new SumoTraciConnection(Inet4Address.getByName("10.211.55.3"), 9001,this);
			connectedCars = new ConcurrentHashMap<String,ConnectedVehicle>();
			
			// the first two steps of this simulation have no vehicles.
			int maximumSteps= 130;
			while(maximumSteps>0)
			{
				conn.nextSimStep();
				Thread.sleep(100);
				maximumSteps--;
			}
			conn.close();
		}
		catch(Exception e) {
			e.printStackTrace();
		}	
	}
	
	@Override
	public void vehicleDeparted(SUMOVehicle vehicle) {
		
		ConnectedVehicle cv = new ConnectedVehicle(vehicle);
		this.connectedCars.put(vehicle.getID(),cv);
		cv.onConnect();
		
	}
	@Override
	public void vehicleArrived(SUMOVehicle vehicle) {
		this.connectedCars.get(vehicle.getID()).onDisconnect();
		this.connectedCars.remove(vehicle.getID());
		
	}
	@Override
	public void vehicleTeleportStarting(SUMOVehicle vehicle) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void vehicleTeleportEnding(SUMOVehicle vehicle) {
		// TODO Auto-generated method stub
		
	}
}
